﻿using System;
using System.Linq;
using System.Collections.Generic;

namespace Data.Repository
{
	public class CashTicketRepository : ICashTicketRepository
	{
		private LinqToECommerceDBDataContext _dbContext;

		#region ICashTicketRepository Members

		public int CreateNewCashTicket(Data.Entity.CashTicket theNewCashTicket)
		{
			if(theNewCashTicket == null)
			{
				return -1;
			}

			int result = 0;

			using(_dbContext = new LinqToECommerceDBDataContext())
			{
				result = _dbContext.ECommerce_CashTicket_Create(theNewCashTicket.Cost, theNewCashTicket.ExpiredDate, theNewCashTicket.CreatedOn, theNewCashTicket.IsUsed, theNewCashTicket.UserID);
			}

			return result;
		}

		public IList<Data.Entity.CashTicket> GetMyCashTicket(Guid userID)
		{
			if(userID == null || Guid.Empty.Equals(userID))
			{
				return null;
			}

			List<ECommerce_GetCashTicket_By_UserResult> lstData;

			using(_dbContext = new LinqToECommerceDBDataContext())
			{
				var data = _dbContext.ECommerce_GetCashTicket_By_User(userID);

				lstData = data.ToList();
			}

				if(lstData != null && lstData.Count > 0)
				{
					var result = new List<Data.Entity.CashTicket>();

					foreach(var ct in lstData)
					{
						var theEntity = new Data.Entity.CashTicket()
						{
							UserID = ct.UserID,
							IsUsed = ct.IsUsed,
							CreatedOn = ct.CreatedOn,
							ExpiredDate = ct.ExpiredDate,
							Cost = ct.Cost,
							CashTicketID = ct.CashTicketID,
							CashTicketNumber = ct.CashTicketNumber
						};

						result.Add(theEntity);
					}

					return result;
				}
				else
				{
					return null;
				}
		}

		public int UpdateCashTicket(Data.Entity.CashTicket theCashTicket)
		{
			if (theCashTicket == null)
			{
				return -1;
			}

			var result = 0;

			using(_dbContext = new LinqToECommerceDBDataContext())
			{
				var dbCashTicket = (from ct in _dbContext.CashTickets
									where ct.CashTicketID.Equals(theCashTicket.CashTicketID)
									select ct).FirstOrDefault();

				if(dbCashTicket == null)
				{
					result = 0;
				}
				else
				{
					dbCashTicket.Cost = theCashTicket.Cost;
					dbCashTicket.ExpiredDate = theCashTicket.ExpiredDate;
					dbCashTicket.IsUsed = theCashTicket.IsUsed;

					_dbContext.SubmitChanges();

					result = 1;
				}
			}

			return result;
		}

		#endregion
	}
}
